document.addEventListener('DOMContentLoaded', function() {
    // 配置toastr提示框
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "3000"
    };

    // 获取token
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    // API基础URL
    const apiUrl = "http://localhost:9999/order/";
    
    // 分页参数
    let currentPage = 1;
    const pageSize = 10;
    let totalPages = 0;
    let totalRecords = 0;

    // 搜索参数
    let searchParams = {
        page: 1,
        pageSize: 10,
        username: '',
        phone: '',
        status: null
    };

    // 订单状态映射
    const orderStatusMap = {
        0: { text: '待付款', class: 'status-pending' },
        1: { text: '待发货', class: 'status-paid' },
        2: { text: '已发货', class: 'status-shipped' },
        3: { text: '已完成', class: 'status-completed' },
        4: { text: '已取消', class: 'status-cancelled' }
    };

    // 订单列表
    function renderOrderList(orders) {
        console.log('Rendering orders:', orders);
        const orderList = $('#orderList');
        orderList.empty();

        if (!orders || orders.length === 0) {
            orderList.append('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
            return;
        }

        orders.forEach(order => {
            console.log('Processing order:', order);
            const status = orderStatusMap[order.status] || { text: '未知', class: '' };
            
            const row = `
                <tr>
                    <td>${order.id || '-'}</td>
                    <td>${order.username || '-'}</td>
                    <td>￥${(order.totalPrice || 0).toFixed(2)}</td>
                    <td><span class="status-badge ${status.class}">${status.text}</span></td>
                    <td>${formatDate(order.createTime)}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn-primary detailBtn" data-id="${order.id}">详情</button>
                            ${getActionButtons(order.status, order.id)}
                        </div>
                    </td>
                </tr>
            `;
            orderList.append(row);
        });
    }

    // 根状态获取操作按钮
    function getActionButtons(status, orderId) {
        let buttons = '';
        switch (status) {
            case 0: // 待付款
                buttons = `
                    <button class="btn-success payBtn" data-id="${orderId}">付款</button>
                    <button class="btn-danger cancelBtn" data-id="${orderId}">取消</button>
                `;
                break;
            case 1: // 待发货
                buttons = `<button class="btn-warning shipBtn" data-id="${orderId}">发货</button>`;
                break;
            case 2: // 已发货
                buttons = `<button class="btn-success completeBtn" data-id="${orderId}">确认收货</button>`;
                break;
        }
        return buttons;
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 渲染分页
    function renderPagination(total) {
        totalRecords = total;
        totalPages = Math.ceil(total / pageSize);
        
        // 更新页码信显示
        $('#pageInfo').text(`第 ${currentPage} 页 / 共 ${totalPages} 页`);
        $('#totalInfo').text(`共 ${totalRecords} 条`);
        
        // 更新按钮状态
        $('#prevPage').prop('disabled', currentPage <= 1);
        $('#nextPage').prop('disabled', currentPage >= totalPages);
        
        console.log('分页信息：', {
            currentPage,
            totalPages,
            totalRecords,
            pageSize
        });
    }

    // 获取订单列表
    function fetchOrderList() {
        console.log('请求参数：', searchParams);
        $.ajax({
            url: `${apiUrl}list`,
            method: 'GET',
            headers: {
                'token': token
            },
            data: searchParams,
            success: function(response) {
                console.log('Response:', response);
                if (response.code === 200) {
                    const pageData = response.data;
                    console.log('Page data:', pageData);
                    if (pageData) {
                        renderOrderList(pageData.records || []);
                        renderPagination(pageData.total || 0);
                    } else {
                        toastr.error('数据格式错误');
                        console.error('Unexpected data format:', pageData);
                    }
                } else {
                    toastr.error(response.msg || '获取订单列表失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('API Error:', error);
                toastr.error('服务器错误，请稍后重试');
            }
        });
    }

    // 获取订单详情
    function fetchOrderDetail(orderId) {
        $.ajax({
            url: `${apiUrl}${orderId}`,
            method: 'GET',
            headers: {
                'token': token
            },
            success: function(response) {
                if (response.code === 200) {
                    const order = response.data;
                    renderOrderDetail(order);
                    $('#orderDetailModal').fadeIn(300);
                } else {
                    toastr.error(response.msg || '获取订单详情失败');
                }
            },
            error: function() {
                toastr.error('服务器错误，请稍后重试');
            }
        });
    }

    // 渲染订单详情
    function renderOrderDetail(order) {
        const status = orderStatusMap[order.status] || { text: '未知', class: '' };
        
        // 基本信息
        $('#detailOrderNo').text(order.id);
        $('#detailUserId').text(order.username);
        $('#detailAmount').text(`￥${(order.totalPrice || 0).toFixed(2)}`);
        $('#detailStatus').html(`<span class="status-badge ${status.class}">${status.text}</span>`);
        $('#detailCreateTime').text(formatDate(order.createTime));

        // 订单商品列表
        const itemsList = $('#orderItemsList');
        itemsList.empty();

        if (order.productName) {
            const row = `
                <tr>
                    <td>${order.productName}</td>
                    <td>1</td>
                    <td>￥${(order.totalPrice || 0).toFixed(2)}</td>
                    <td>￥${(order.totalPrice || 0).toFixed(2)}</td>
                </tr>
            `;
            itemsList.append(row);
        } else {
            itemsList.append('<tr><td colspan="4" class="text-center">暂无商品数据</td></tr>');
        }

        // 状态操作按钮
        const statusActions = $('.status-actions');
        statusActions.empty();
        statusActions.append(getActionButtons(order.status, order.id));
    }

    // 更新订单状态
    function updateOrderStatus(orderId, status, successMsg) {
        $.ajax({
            url: `${apiUrl}status/${status}/${orderId}`,
            method: 'PUT',
            headers: {
                'token': token
            },
            success: function(response) {
                if (response.code === 200) {
                    toastr.success(successMsg);
                    $('#orderDetailModal').fadeOut(300);
                    fetchOrderList();
                } else {
                    toastr.error(response.msg || '操作失败');
                }
            },
            error: function() {
                toastr.error('服务器错误，请稍后重试');
            }
        });
    }

    // 事件绑定
    // 搜索按钮点击事件
    $('#searchBtn').on('click', function() {
        currentPage = 1;  // 重置页码
        const statusValue = $('#searchStatus').val();
        searchParams = {
            page: currentPage,
            pageSize: 10,
            username: $('#searchOrderNo').val().trim(), // 用户名搜索
            phone: $('#searchUserId').val().trim(),     // 手机号搜索
            status: statusValue === '' ? null : parseInt(statusValue)
        };
        console.log('搜索参数：', searchParams);
        fetchOrderList();
    });

    // 重置按钮点击事件
    $('#resetBtn').on('click', function() {
        $('#searchOrderNo').val('');
        $('#searchUserId').val('');
        $('#searchStatus').val('');
        currentPage = 1;  // 重置页码
        searchParams = {
            page: currentPage,
            pageSize: 10,
            username: '',
            phone: '',
            status: null
        };
        console.log('重置参数：', searchParams);
        fetchOrderList();
    });

    // 查看详情按钮点击事件
    $(document).on('click', '.detailBtn', function() {
        const orderId = $(this).data('id');
        fetchOrderDetail(orderId);
    });

    // 关闭详情弹窗
    $('.close, #closeDetail').on('click', function() {
        $('#orderDetailModal').fadeOut(300);
    });

    // 付款按钮点击事件
    $(document).on('click', '.payBtn', function() {
        const orderId = $(this).data('id');
        if (confirm('确认要将订单标记为已付款吗？')) {
            updateOrderStatus(orderId, 1, '订单已付款');
        }
    });

    // 发货按钮点击事件
    $(document).on('click', '.shipBtn', function() {
        const orderId = $(this).data('id');
        if (confirm('确认要将订单标记为已发货吗？')) {
            updateOrderStatus(orderId, 2, '订单已发货');
        }
    });

    // 确认收货按钮点击事件
    $(document).on('click', '.completeBtn', function() {
        const orderId = $(this).data('id');
        if (confirm('确认要将订单标记为已完成吗？')) {
            updateOrderStatus(orderId, 3, '订单已完成');
        }
    });

    // 取消订单按钮点击事件
    $(document).on('click', '.cancelBtn', function() {
        const orderId = $(this).data('id');
        if (confirm('确认要取消订单吗？此操作不可恢复！')) {
            updateOrderStatus(orderId, 4, '订单已取消');
        }
    });

    // 分页事件
    $('#prevPage').on('click', function() {
        if (currentPage > 1) {
            currentPage--;
            searchParams.page = currentPage;
            console.log('上一页：', searchParams);
            fetchOrderList();
        }
    });

    $('#nextPage').on('click', function() {
        if (currentPage < totalPages) {
            currentPage++;
            searchParams.page = currentPage;
            console.log('下一页：', searchParams);
            fetchOrderList();
        }
    });

    // 初始化加载
    fetchOrderList();
}); 